package ruru.client.ui.widgets;

import ruru.client.backend.RuruUtility;
import ruru.client.backend.rpcWrapper.RaidLootRowWrapper;
import ruru.client.backend.rpcWrapper.RaidWrapper;
import ruru.client.services.DataService;
import ruru.client.services.DataServiceAsync;
import ruru.client.ui.widgets.sortableTable.ComparableHTML;
import ruru.client.ui.widgets.sortableTable.Sortable;
import ruru.client.ui.widgets.sortableTable.SortableTable;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MouseListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.RowFormatter;

public class RaidWidget extends Composite {
	VerticalPanel widget;

	final HorizontalPanel titlePanel;
	NoFocusMouseListenerPanel titleFocus;
	Label titleLabel;
	Image treeIcon;
	boolean titleOpen;
	boolean initialized;

	VerticalPanel body;
	FlexTable stats; // displays raid id, dungeon, startTime, endTime,
	// participants
	HTML raidDesc;
	Label pointsEarned;
	Label duration;
	Label end;
	Label loadingLabel;
	HTML participants;
	Image blank;

	SortableTable loot;

	Image treeOpen = new Image("images/tree-open.gif");
	Image treeClosed = new Image("images/tree-closed.gif");
	Image treeBlank = new Image("images/tree-blank.gif");

	static DateTimeFormat hourFormat = DateTimeFormat.getFormat("h:mma");
	static DateTimeFormat dateFormat = DateTimeFormat.getFormat("EEE MM-dd-yyyy");
	
	RaidWrapper raid;
	final int index;

	public RaidWidget(final String title, final int index) {
		initialized = false;
		this.index = index;
		widget = new VerticalPanel();

		titlePanel = new HorizontalPanel();
		// titleLabel = new Label(dateFormat.format(raid.getStartDate()) + " " + raid.getFullDungeonName());
		titleLabel = new Label(title);
		treeIcon = treeClosed;
		titleOpen = false;

		titlePanel.add(treeIcon);
		titlePanel.add(titleLabel);
		loot = new SortableTable();

		titleFocus = new NoFocusMouseListenerPanel(titlePanel);

		titleFocus.addMouseListener(new MouseListener() {
			public void onMouseDown(Widget sender, int x, int y) {}

			public void onMouseEnter(Widget sender) {
			// titleLabel.addStyleName("underlined");
			}

			public void onMouseLeave(Widget sender) {
			// titleLabel.removeStyleName("underlined");
			}

			public void onMouseMove(Widget sender, int x, int y) {}

			public void onMouseUp(Widget sender, int x, int y) {
				if(titleOpen) {
					titleLabel.removeStyleName("selected");

					treeIcon.setUrl("images/tree-closed.gif");
					titleOpen = false;
					body.setVisible(false);
					loot.removeStyleName("raid-bottom-padding");
				} else {
					loot.addStyleName("raid-bottom-padding");
					// titleLabel.addStyleName("selected");
					treeIcon.setUrl("images/tree-open.gif");
					titleOpen = true;
					body.setVisible(true);
					getRaidByIndex(index);
					

				}
			}
		});

		titleFocus.addStyleName("raid-title");

		body = new VerticalPanel();
		body.setVisible(false);
		loadingLabel = new Label("Loading...");
		loadingLabel.addStyleName("raid-loading-label");
		body.add(loadingLabel);

		widget.add(titleFocus);
		widget.add(body);
		widget.addStyleName("raid");
		initWidget(widget);
	}
	
	public void getRaidByIndex(int index) {
		DataServiceAsync ds = (DataServiceAsync) GWT.create(DataService.class);

		ServiceDefTarget endpoint = (ServiceDefTarget) ds;
		String moduleRelativeURL = GWT.getModuleBaseURL() + "/DataService";
		endpoint.setServiceEntryPoint(moduleRelativeURL);

		AsyncCallback callback = new AsyncCallback() {
			public void onSuccess(Object result) {
				raid = (RaidWrapper) result;
				
				DeferredCommand.addCommand(new Command() {
					public void execute() {
						if(!initialized) {
							stats = new FlexTable();
							blank = treeBlank;
							
							raidDesc = new HTML("<i>" + raid.getDescription() + "</i>");
							duration = new Label("Duration: " + hourFormat.format(raid.getStartDate()) + " - "
									+ hourFormat.format(raid.getEndDate()));

							pointsEarned = new Label("DKP: "
									+ RuruUtility.twoDecimals(raid.getDkpAwarded()));
							
							HorizontalPanel hp = new HorizontalPanel();
							hp.add(pointsEarned);
							hp.add(duration);
							hp.setCellHorizontalAlignment(pointsEarned, HasHorizontalAlignment.ALIGN_LEFT);
							hp.setCellHorizontalAlignment(duration, HasHorizontalAlignment.ALIGN_RIGHT);
							
//							List memList = new ArrayList();
//							for(int i = 0; i < raid.getParticipants().size(); i++) {
//								Raider raider = (Raider) raid.getParticipants().get(i);
//
//								memList.add(raider);
//							}
//
//							Collections.sort(memList);
//							StringBuffer members = new StringBuffer();
//							for(int i = 0; i < memList.size(); i++) {
//								Raider raider = (Raider) memList.get(i);
//								members.append("<span class='" + raider.getRaidClass() + "'>" + raider.getName()
//										+ " </span>");
//							}

							participants = new HTML("<span class='raid-widget-stats'> Participants: </span>" + raid.getHtmlMemberStr());
							initTable(raid);
							
							stats.setWidget(0, 0, treeBlank);
							stats.getFlexCellFormatter().setRowSpan(0, 0, 5);

							stats.setWidget(1, 1, hp);
							stats.setWidget(2, 1, raidDesc);
							stats.setWidget(3, 1, participants);

							raidDesc.addStyleName("raid-widget-stats");
							duration.addStyleName("raid-widget-stats");
							pointsEarned.addStyleName("raid-widget-stats");
							duration.addStyleName("raid-widget-stats");
							hp.addStyleName("raid-widget-stats");
							hp.setWidth("100%");

							if(!(raid.getRaidLootWrapperRows().isEmpty())) {
								stats.setWidget(4, 1, loot);
							}

							stats.setCellSpacing(0);
							// stats.setWidth("100%");
							body.remove(loadingLabel);
							body.add(stats);
							body.addStyleName("raid-widget-body");
							initialized = true;
						}
					}
				});
			}

			public void onFailure(Throwable caught) {
				System.out.println("in client: getRaidTitles failure");
				caught.printStackTrace();
			}
		};

		ds.getRaidByIndex(index, callback);
	}

	private void initTable(RaidWrapper raid) {
		loot.setWidth("100%");

		loot.addColumnHeader("Loot", 0);
		loot.addColumnHeader("Recipient", 1);
		loot.addColumnHeader("Boss", 2);
		loot.addColumnHeader("Cost", 3);

		int i;
		for(i = 0; i < raid.getRaidLootWrapperRows().size(); i++) {
			RaidLootRowWrapper assign = (RaidLootRowWrapper) raid.getRaidLootWrapperRows().get(i);
			ItemLink itemLink = new ItemLink(assign.getItemName());

			loot.setValue(i + 1, 0, itemLink);
			loot.setValue(i + 1, 1, assign.getRecipientName());
			loot.setValue(i + 1, 2, assign.getBossName());
			loot.setValue(i + 1, 3, new ComparableHTML(RuruUtility.twoDecimals(assign.getDkpCost())));
		}

		for(int k = 0; k < i + 1; k++) {
			for(int j = 0; j < 4; j++) {
				CellFormatter cellFormatter = loot.getCellFormatter();
				cellFormatter.addStyleName(k, j, "sortable-table-cell");
				if(j == 1 || j == 2 || j == 3) {
					cellFormatter.addStyleName(k, j, "text-align-right");
				}
				// if(j > 0) {
				// cellFormatter.addStyleName(k, j, "text-center");
				//				}
			}
		}

		loot.addStyleName("sortable-table");
		loot.addStyleName("raid-loot-table");
		loot.setCellSpacing(0);

		// Set Style Name for the header
		RowFormatter rowFormatter = loot.getRowFormatter();
		rowFormatter.addStyleName(0, "standings-tableHeader");

		CellFormatter cellFormatter = loot.getCellFormatter();
		// Set the styles for the headers
		for(int row = 0; row < loot.getRowCount(); row++) {
			cellFormatter.setWidth(row, 0, "45%");
			cellFormatter.setWidth(row, 1, "15%");
			cellFormatter.setWidth(row, 2, "25%");
			cellFormatter.setWidth(row, 3, "15%");
		}
		
		for(int row = 1; row < loot.getRowCount(); row++) {
			rowFormatter.addStyleName(row, "row");
		}

		loot.forceSort(2, Sortable.SORT_ASC);
	}
}